package com.example.proxy.cgld_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Calendar;

public class CglibProxyFactory implements MethodInterceptor {

    private Object target;

    public CglibProxyFactory(Object target) {
        this.target = target;
    }


    public Object getLogProxy(Object target) {
        //增强器
        Enhancer enhancer = new Enhancer();

        //设置代理类的父类字节码对象
        enhancer.setSuperclass(target.getClass());

        //设置回调 就是当前嘞
        enhancer.setCallback(this);


        return enhancer.create();
    }


    /**
     * @param o           代理方法
     * @param method      目标对象中的方法的 method 实例
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        //时间处理
        Calendar instance = Calendar.getInstance();

        System.out.println("开始记录日志 = ");
        Object invoke = methodProxy.invokeSuper(o, objects);

        System.out.println("结束记录日志 ");

        return invoke;
    }
}
